import React, { useState, useEffect } from 'react';
import { message } from 'antd';
import { http, API_PATH } from '../utils/http/config';

// 定义登录响应类型
interface LoginResponse {
    access_token: string;
    token_type: string;
}

// 定义用户信息类型
interface UserInfo {
    username: string;
    email: string;
    role: string;
    display_name: string;
}

const Login: React.FC = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);

    // 组件挂载时检查是否已登录
    useEffect(() => {
        // 如果已经有token，清除它以确保用户可以重新登录
        const token = localStorage.getItem('access_token');
        if (token) {
            localStorage.removeItem('access_token');
            localStorage.removeItem('token_type');
            // 同时清除用户信息
            sessionStorage.removeItem('userInfo');
        }
    }, []);

    // 获取用户信息
    const fetchUserInfo = async () => {
        try {
            const response = await http.get<UserInfo>(API_PATH.AUTH.ME);
            if (response.code === 0 && response.data) {
                // 存储用户信息到sessionStorage
                sessionStorage.setItem('userInfo', JSON.stringify(response.data));
                console.log(response.data);
            } else {
                console.warn('获取用户信息失败:', response.message);
            }
        } catch (error) {
            console.error('获取用户信息错误:', error);
        }
    };

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!username || !password) {
            message.error('用户名和密码不能为空');
            return;
        }

        setLoading(true);

        try {
            // 使用http实例调用登录接口，并指定返回类型
            const response = await http.post<LoginResponse>(API_PATH.AUTH.LOGIN, {
                username,
                password
            });

            if (response.code === 0 && response.data) {
                // 登录成功，存储token
                localStorage.setItem('access_token', response.data.access_token);
                localStorage.setItem('token_type', response.data.token_type);

                // 登录成功后获取用户信息
                await fetchUserInfo();

                message.success('登录成功');

                // 跳转到首页
                window.location.href = '/';
            } else if (response.code === 401) {
                // 处理401未授权错误
                message.error('用户名或密码错误');
            } else {
                message.error(response.message || '登录失败');
            }
        } catch (error: unknown) {
            console.error('登录错误:', error);
            // 检查是否为401错误
            const axiosError = error as { code?: number; response?: { status?: number } };
            if (axiosError?.code === 401 || axiosError?.response?.status === 401) {
                message.error('用户名或密码错误');
            } else {
                message.error('登录失败，请检查网络连接或稍后重试');
            }
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
            <div className="max-w-md w-full space-y-8">
                <div>
                    <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">登录智能助手</h2>
                </div>
                <form className="mt-8 space-y-6" onSubmit={handleLogin}>
                    <div className="rounded-md shadow-sm -space-y-px">
                        <div>
                            <label htmlFor="username" className="sr-only">用户名</label>
                            <input
                                id="username"
                                name="username"
                                type="text"
                                required
                                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
                                placeholder="用户名"
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                            />
                        </div>
                        <div>
                            <label htmlFor="password" className="sr-only">密码</label>
                            <input
                                id="password"
                                name="password"
                                type="password"
                                required
                                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
                                placeholder="密码"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                            />
                        </div>
                    </div>

                    <div>
                        <button
                            type="submit"
                            disabled={loading}
                            className={`group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${loading ? 'opacity-70 cursor-not-allowed' : ''}`}
                        >
                            {loading ? '登录中...' : '登录'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default Login; 